use crate::esl::{ESLConnection, ESLMessage};
use anyhow::Result;
use std::collections::HashMap;
use tokio::time::Duration;
use tracing::{debug, error, info};

pub struct FreeSwitchClient {
    connection: ESLConnection,
}

impl FreeSwitchClient {
    pub async fn connect(host: &str, port: u16) -> Result<Self> {
        let connection = ESLConnection::connect(host, port).await?;
        Ok(Self { connection })
    }

    pub async fn authenticate(&mut self, password: &str) -> Result<()> {
        self.connection.authenticate(password).await
    }

    pub async fn make_call(&mut self, number: &str, timeout: u64) -> Result<String> {
        info!("开始拨打电话: {}", number);
        
        // 创建呼叫命令
        let call_cmd = format!(
            "bgapi originate {{origination_caller_id_number=1000,origination_caller_id_name=TestUser,originate_timeout={}}}user/1000 {} &park()",
            timeout, number
        );

        let response = self.connection.send_command(&call_cmd).await?;
        debug!("呼叫响应: {:?}", response);

        if let Some(job_uuid) = response.get_header("Job-UUID") {
            info!("呼叫任务UUID: {}", job_uuid);
            Ok(job_uuid.clone())
        } else {
            Err(anyhow::anyhow!("未获取到呼叫任务UUID"))
        }
    }

    pub async fn hangup_call(&mut self, uuid: &str) -> Result<()> {
        info!("挂断通话: {}", uuid);
        
        let hangup_cmd = format!("bgapi uuid_kill {}", uuid);
        let response = self.connection.send_command(&hangup_cmd).await?;
        
        debug!("挂断响应: {:?}", response);
        Ok(())
    }

    pub async fn get_channel_info(&mut self, uuid: &str) -> Result<ESLMessage> {
        let info_cmd = format!("bgapi uuid_getvar {} all", uuid);
        self.connection.send_command(&info_cmd).await
    }

    pub async fn subscribe_events(&mut self) -> Result<()> {
        info!("订阅所有事件");
        let event_cmd = "event plain ALL";
        let response = self.connection.send_command(event_cmd).await?;
        debug!("事件订阅响应: {:?}", response);
        Ok(())
    }

    pub async fn listen_for_events(&mut self, duration: Option<Duration>) -> Result<()> {
        info!("开始监听事件...");
        
        let timeout = duration.unwrap_or(Duration::from_secs(60));
        let start_time = std::time::Instant::now();
        
        while start_time.elapsed() < timeout {
            match self.connection.read_event().await {
                Ok(Some(event)) => {
                    self.handle_event(&event).await;
                }
                Ok(None) => {
                    // 连接已关闭
                    break;
                }
                Err(e) => {
                    error!("读取事件失败: {}", e);
                    break;
                }
            }
        }
        
        info!("事件监听结束");
        Ok(())
    }

    async fn handle_event(&self, event: &ESLMessage) {
        if let Some(event_name) = event.get_event_name() {
            match event_name.as_str() {
                "CHANNEL_CREATE" => {
                    info!("通道已创建 - UUID: {:?}", event.get_uuid());
                }
                "CHANNEL_ANSWER" => {
                    info!("通话已接通 - UUID: {:?}", event.get_uuid());
                }
                "CHANNEL_HANGUP" => {
                    if let Some(hangup_cause) = event.get_header("Hangup-Cause") {
                        info!("通话已挂断 - UUID: {:?}, 原因: {}", event.get_uuid(), hangup_cause);
                    } else {
                        info!("通话已挂断 - UUID: {:?}", event.get_uuid());
                    }
                }
                "CHANNEL_DESTROY" => {
                    info!("通道已销毁 - UUID: {:?}", event.get_uuid());
                }
                "BACKGROUND_JOB" => {
                    if let Some(job_uuid) = event.get_header("Job-UUID") {
                        info!("后台任务完成 - Job UUID: {}", job_uuid);
                    }
                }
                _ => {
                    debug!("收到事件: {} - UUID: {:?}", event_name, event.get_uuid());
                }
            }
        }
    }

    pub async fn list_channels(&mut self) -> Result<Vec<HashMap<String, String>>> {
        info!("获取通道列表");
        
        let list_cmd = "bgapi show channels";
        let response = self.connection.send_command(&list_cmd).await?;
        
        let mut channels = Vec::new();
        for line in response.body.lines() {
            if line.contains("|") && !line.contains("UUID") {
                let parts: Vec<&str> = line.split('|').collect();
                if parts.len() >= 4 {
                    let mut channel = HashMap::new();
                    channel.insert("uuid".to_string(), parts[0].trim().to_string());
                    channel.insert("direction".to_string(), parts[1].trim().to_string());
                    channel.insert("created".to_string(), parts[2].trim().to_string());
                    channel.insert("name".to_string(), parts[3].trim().to_string());
                    channels.push(channel);
                }
            }
        }
        
        info!("找到 {} 个活动通道", channels.len());
        Ok(channels)
    }

    pub async fn get_status(&mut self) -> Result<ESLMessage> {
        info!("获取FreeSWITCH状态");
        self.connection.send_command("status").await
    }
} 